#ifndef DEVICECONTROLLER_H
#define DEVICECONTROLLER_H

#include <QObject>
#include <QTimer>
#include <QSerialPort>
#include <QDateTime>
#include "auditlogger.h"

// 设备状态枚举
typedef enum {
    DEVICE_IDLE = 0,        // 设备空闲
    DEVICE_SAMPLING,        // 正在采样
    DEVICE_STOPPING,        // 正在停止
    DEVICE_ERROR,           // 设备错误
    DEVICE_MAINTENANCE      // 维护模式
} DeviceStatus;

// 采样模式枚举
typedef enum {
    SAMPLING_TIMED = 0,     // 定时采样
    SAMPLING_VOLUME         // 定量采样
} SamplingMode;

// 设备参数结构体
typedef struct {
    int flow_rate;          // 流量 (L/min)
    int sampling_time;      // 采样时间 (秒)
    int sampling_volume;    // 采样体积 (L)
    int battery_level;      // 电池电量 (%)
    int fan_speed;          // 风机转速 (RPM)
    float temperature;      // 温度 (°C)
    float humidity;         // 湿度 (%)
} DeviceParameters;

// 采样记录结构体
typedef struct {
    QDateTime start_time;   // 开始时间
    QDateTime end_time;     // 结束时间
    int actual_volume;      // 实际采样体积
    int actual_time;        // 实际采样时间
    SamplingMode mode;      // 采样模式
    DeviceStatus status;    // 采样状态
    QString operator_id;    // 操作员ID
} SamplingRecord;

class DeviceController : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int flowRate READ getFlowRate NOTIFY flowRateChanged)
    Q_PROPERTY(int batteryLevel READ getBatteryLevel NOTIFY batteryLevelChanged)
    Q_PROPERTY(int fanSpeed READ getFanSpeed NOTIFY fanSpeedChanged)
    Q_PROPERTY(QString deviceStatus READ getDeviceStatusString NOTIFY deviceStatusChanged)
    Q_PROPERTY(float temperature READ getTemperature NOTIFY temperatureChanged)
    Q_PROPERTY(float humidity READ getHumidity NOTIFY humidityChanged)

public:
    explicit DeviceController(QObject *parent = nullptr);
    ~DeviceController();

    // 设备初始化
    bool initializeDevice();
    void shutdownDevice();

    // 设备控制方法 (使用C风格语法)
    Q_INVOKABLE bool startFan(int speed);
    Q_INVOKABLE bool stopFan();
    Q_INVOKABLE bool startSampling(SamplingMode mode, int parameter);
    Q_INVOKABLE bool stopSampling();
    
    // 参数设置方法
    Q_INVOKABLE bool setFlowRate(int rate);
    Q_INVOKABLE bool setSamplingTime(int seconds);
    Q_INVOKABLE bool setSamplingVolume(int volume);
    
    // 状态查询方法
    Q_INVOKABLE int getFlowRate() const;
    Q_INVOKABLE int getBatteryLevel() const;
    Q_INVOKABLE int getFanSpeed() const;
    Q_INVOKABLE float getTemperature() const;
    Q_INVOKABLE float getHumidity() const;
    Q_INVOKABLE DeviceStatus getDeviceStatus() const;
    Q_INVOKABLE QString getDeviceStatusString() const;
    
    // 采样记录管理
    Q_INVOKABLE QList<QVariant> getSamplingHistory() const;
    Q_INVOKABLE bool clearSamplingHistory();
    
    // 设备自检
    Q_INVOKABLE bool performSelfTest();
    Q_INVOKABLE QString getLastError() const;

    // 设置审计日志记录器
    void setAuditLogger(AuditLogger* logger);

signals:
    void flowRateChanged(int rate);
    void batteryLevelChanged(int level);
    void fanSpeedChanged(int speed);
    void deviceStatusChanged(DeviceStatus status);
    void temperatureChanged(float temp);
    void humidityChanged(float humidity);
    void samplingStarted(SamplingMode mode);
    void samplingCompleted(const SamplingRecord& record);
    void deviceError(const QString& error);
    void batteryLow(int level);

private slots:
    void updateDeviceStatus();
    void onSamplingTimer();
    void onSerialDataReceived();

private:
    // 私有成员变量
    DeviceParameters m_parameters;
    DeviceStatus m_status;
    SamplingMode m_currentMode;
    QDateTime m_samplingStartTime;
    QList<SamplingRecord> m_samplingHistory;
    QString m_lastError;
    
    // Qt对象
    QTimer* m_statusTimer;
    QTimer* m_samplingTimer;
    QSerialPort* m_serialPort;
    AuditLogger* m_auditLogger;
    
    // 私有方法 (使用C风格语法)
    bool sendCommand(const char* command);
    bool readDeviceResponse(char* buffer, int maxSize);
    void logDeviceOperation(const char* operation, const char* details);
    void updateBatteryLevel();
    void checkFlowRate();
    bool validateParameters();
    
    // 设备通信协议方法
    bool connectToDevice();
    void disconnectFromDevice();
    bool isDeviceConnected() const;
};

// C风格的辅助函数
extern "C" {
    const char* deviceStatusToString(DeviceStatus status);
    const char* samplingModeToString(SamplingMode mode);
    int calculateSamplingTime(int volume, int flowRate);
    bool validateFlowRate(int rate);
    bool validateSamplingVolume(int volume);
}

#endif // DEVICECONTROLLER_H